import React from 'react'
import {connect} from 'react-redux'
import baseService from 'share/base.service';
import SlideFrame from 'components/slide-frame';
import ListSelector from 'components/list-selector';
import { message, Select, Button, Badge, Alert } from "antd";
import {messages, queryCurrencyPrecision} from "share/common";
import 'styles/finance-setting/audit-opinion/audit-opinion.scss';
import LoanRule from 'containers/finance-setting/loan-max/loan-rule';
import LoanService from 'containers/finance-setting/loan-max/loan-service';
import ResizeTable from 'components/resize-table'
const Option = Select.Option;

class LoanMax extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      setOfBooksId: [],
      onSetOfBooksId: this.props.company.setOfBooksId,
      onSetOfBooksName: this.props.company.setOfBooksName,
      data: [],
      loading: false,
      columns: [
        {title: messages('finance-setting.key150')/*借款类型*/, dataIndex: 'loanAmountType'},
        {title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode'},
        {title: messages('finance-setting.key110')/*金额*/, dataIndex: 'amountMax', render: (value,record) => {
          return this.filterMoney(value,queryCurrencyPrecision(record.currencyCode));
          }},
        {title: messages('common.column.status')/*状态*/, dataIndex: 'enabled', render: value => {
          return value ? <Badge text={messages('common.status.enable')/*启用*/} status={'success'}/> :
            <Badge text={messages('common.status.disable')/*禁用*/} status={'error'}/>}}
      ],
      pagination: {
        total: 0,
      },
      page: 0,
      show: false,
      listShow: false,
      groupShow: false,
      editRecord: {},
      title: '',
      userIds: [],
      userGroups: []
    }
  }

  componentWillMount() {
    if(this.props.tenantMode){
      const { columns } = this.state;
      columns.push({title: messages('common.operation')/*操作*/, dataIndex: 'operation', render: (value,record) => {
          return (
            <div>
              <a onClick={(e) => this.editShow(e,'show',record)}>{messages('common.edit')/*编辑*/}</a>
              <span className="ant-divider"  style={{backgroundColor:'#63B8EE'}}/>
              <a onClick={(e) => this.editShow(e,'listShow',record)}>{messages('finance-setting.key151')/*分配*/}</a>
              <span className="ant-divider"  style={{backgroundColor:'#63B8EE'}}/>
              <a onClick={(e) => this.editShow(e,'groupShow',record)}>{messages('finance-setting.key210')/*分配人员组*/}</a>
            </div>
          )}});
      this.setState(columns);
    }
    this.getSetOfBook();
    this.getList();
  }

  //获取帐套
  getSetOfBook = () => {
    baseService.getSetOfBooksByTenant().then(res => {
      this.setState({setOfBooksId:res.data})
    }).catch(() => {
      message.error(messages('finance-setting.key65'/*出错了*/));
    })
  };

  //获取列表
  getList(){
    const { onSetOfBooksId, page } = this.state;
    this.setState({loading: true});
    LoanService.getLoanAmountMaxList(onSetOfBooksId,page).then(res => {
      this.setState({
        loading: false,
        data: res.data,
        pagination: {
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangePager,
          current: page + 1
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  }

  //帐套更换
  handleChangeBookId = (value) => {
    const { setOfBooksId } = this.state;
    let res = '';
    setOfBooksId.map(item => {
      item.id === value && (res = item.setOfBooksName);
    });
    this.setState({onSetOfBooksId: value,onSetOfBooksName: res},() => {
      this.getList();
    });
  };

  //分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  //编辑||分配
  editShow = (e,type,record) => {
    e.stopPropagation();
    let userIds = [], userGroups = [];
    record.userIds && record.userIds.map(item => {
      userIds.push({id: item});
    });
    record.userGroups && record.userGroups.map(item => {
      userGroups.push({id: item});
    });
    let temp = {
      editRecord: record,
      title: messages('finance-setting.key152')/*借款单金额控制*/,
      userIds,
      userGroups
    };
    temp[type] = true;
    this.setState(temp);
  };

  handleSelectAddition = (value, type) => {
    const { editRecord } = this.state;
    let temp = [];
    value.result.map(item => {
      temp.push(item.id);
    });
    LoanService.assignUsers(editRecord.id, editRecord.loanTypeId, type, temp).then(() => {
      this.setState({ listShow: false, groupShow: false });
      this.getList();
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  handleAdd  = () => {
    this.setState({
      title: messages('finance-setting.key113')/*新建借款单金额控制*/,
      editRecord: {}
    },() => {
      this.setState({show: true});
    })
  };

  render(){
    const { setOfBooksId, data, loading, pagination, columns, show, onSetOfBooksId, editRecord, listShow, title, userIds,
      onSetOfBooksName, groupShow, userGroups } = this.state;
    return(
      <div className="audit-opinion">
        <div className="audit-opinion-title">{messages('finance-setting.key66'/*帐套：*/)}
          <Select onChange={e => this.handleChangeBookId(e)} defaultValue={`${this.props.company.setOfBooksName}`} disabled={!this.props.tenantMode}>
            {
              setOfBooksId.map(item => {
                return <Option key={item.id} title={item.setOfBooksName}>{item.setOfBooksName}</Option>
              })
            }
          </Select>
          <Alert
            type={'info'}
            showIcon
            message={messages('finance-setting.key211')/*可同时「分配人员」或「分配人员组」，同一借款类型的不同上限规则中，优先匹配「分配人员」；若无「分配人员」规则命中，但同时命中多个「分配人员组」规则，则取最低的上限金额最低；*/}
          />
          <div style={{margin:'10px 0px'}}>
            <Button type={'primary'} disabled={!this.props.tenantMode} onClick={this.handleAdd}>{messages('common.create')/*新建*/}</Button>
          </div>
          <ResizeTable
            dataSource={data}
            columns={columns}
            rowKey={'id'}
            bordered
            pagination={pagination}
            loading={loading}
          />
        </div>
        <SlideFrame show={show}
                    title={title}
                    params={{
                      show,
                      setOfBooksId: onSetOfBooksId,
                      setOfBooksName: onSetOfBooksName,
                      editRecord
                    }}
                    content={LoanRule}
                    onClose={(isRefresh) => {
                      this.setState({show: false});
                      isRefresh === true && this.getList();
                    }}
                    afterClose={(isRefresh) => {
                      this.setState({show: false});
                      isRefresh === true && this.getList();
                    }}/>
        <ListSelector
          visible={listShow}
          type="loan-max-users"
          extraParams={{ setOfBooksId: onSetOfBooksId }}
          selectedData={userIds}
          onOk={value => this.handleSelectAddition(value, 'USER')}
          onCancel={() => this.setState({ listShow: false })}
        />
        <ListSelector
          visible={groupShow}
          type="support_failure_user_group"
          extraParams={{ setOfBooksId: onSetOfBooksId }}
          selectedData={userGroups}
          onOk={value => this.handleSelectAddition(value, 'GROUP')}
          onCancel={() => this.setState({ groupShow: false })}
        />
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(LoanMax);
